package com.qidian.study.service.impl;

import com.qidian.study.dao.ContentDAO;
import com.qidian.study.dao.impl.ContentDAOImpl;
import com.qidian.study.pojo.Content;
import com.qidian.study.service.ContentService;
import com.qidian.study.util.JsonTools;
import com.qidian.study.util.RedisUtil;
import com.qidian.study.util.pojo.LayuiTableDTO;
import com.qidian.study.util.pojo.VideoResponse;

import java.util.List;
import java.util.Random;

/**
 * @author 戴着假发的程序员
 * @company 起点编程
 */
public class ContentServiceImpl implements ContentService {
    private ContentDAO contentDAO = new ContentDAOImpl();
    @Override
    public VideoResponse save(Content content) {
        // 清理缓存
        String key = "CONTENT_"+content.getCatId();
        RedisUtil.del(key);
        // 根据数据
        int result = contentDAO.save(content);
        // 开启一个子线程等一会在清理
        new Thread(()->{
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 等500毫秒，再删除key
            RedisUtil.del(key);
        }).start();
        return result==1?VideoResponse.ok():VideoResponse.error();
    }

    @Override
    public VideoResponse update(Content content) {
        return contentDAO.update(content)==1?VideoResponse.ok():VideoResponse.error();
    }

    @Override
    public VideoResponse queryById(Long contentId) {
        return VideoResponse.ok("OK",contentDAO.queryById(contentId));
    }

    @Override
    public VideoResponse queryAll() {
        return VideoResponse.ok("OK",contentDAO.queryAll());
    }

    @Override
    public LayuiTableDTO queryByPage(int page, int size, Content content) {
        LayuiTableDTO dto = new LayuiTableDTO();
        int total = contentDAO.count(content);
        List<Content> contents = contentDAO.queryByPage(page, size, content);
        dto.setCode(0);
        dto.setCount(total);
        dto.setData(contents);
        return dto;
    }

    public VideoResponse queryByCatId(Long catId){
        // 从redis中查询
        String key = "CONTENT_"+catId;
        // 判断key是否存在
        if(RedisUtil.exists(key)){
            String json = RedisUtil.get(key);
            if(json!=null && !"".equals(json)){
                // 将json转换为列表
                List<Content> contents = JsonTools.json2list(json, Content.class);
                return VideoResponse.ok("ok",contents);
            }
        }
        // redis中没有数据
        List<Content> contents = contentDAO.queryByCatId(catId);
        // 将数据给redis中存储一份
        RedisUtil.set(key,JsonTools.object2json(contents));
        // 设置时间
        RedisUtil.expire(key,60*30 +(60 * (new Random().nextInt(20))));
        return VideoResponse.ok("ok",contents);
    }
}
